package gold.digger;

import gold.vo.TreeNode;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC173 {
    public long startExecuteTime = System.currentTimeMillis();


    class BSTIterator {

        Stack<TreeNode> stack = new Stack<>();

        public BSTIterator(TreeNode root) {
            stack.push(root);
            while (stack.peek().left != null) {
                stack.push(stack.peek().left);
            }
        }

        public int next() {
            TreeNode top = stack.pop();
            int topVal = top.val;
            if (top.right != null) {
                stack.push(top.right);
                while (stack.peek().left != null) {
                    stack.push(stack.peek().left);
                }
            }

            return topVal;
        }

        public boolean hasNext() {
            return !stack.isEmpty();
        }
    }


    class BSTIterator_Old {

        Stack<TreeNode> stack = new Stack();

        public BSTIterator_Old(TreeNode root) {
            while (root != null) {
                this.stack.push(root);
                root = root.left;
            }
        }

        /**
         * @return the next smallest number
         */
        public int next() {

            TreeNode cur = stack.pop();
            int nextVal = cur.val;
            cur = cur.right;
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            return nextVal;
        }

        /**
         * @return whether we have a next smallest number
         */
        public boolean hasNext() {
            return !stack.isEmpty();
        }
    }


    public boolean solve(TreeNode root) {
        BSTIterator iterator = new BSTIterator(root);
        iterator.next();    // return 3
        iterator.next();    // return 7
        iterator.hasNext(); // return true
        iterator.next();    // return 9
        iterator.hasNext(); // return true
        iterator.next();    // return 15
        iterator.hasNext(); // return true
        iterator.next();    // return 20
        iterator.hasNext(); // return false

        return true;
    }


    public static void main(String[] args) throws Exception {
        LC173 an = new LC173();
        TreeNode root = TreeNode.createTree("[7,3,15,null,null,9,20]");
        System.out.println(an.solve(root));

        System.out.println("\nanswer total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
